# -*- coding: utf-8 -*-
# Gestión y diseño gráfico de consulta RSS, mediante módulo feedparser.

## vipera, un diseñador de aplicaciones para Python
##    Copyright (C) 2011 Ángel Luis García García
##
##    This program is free software: you can redistribute it and/or modify
##    it under the terms of the GNU General Public License as published by
##    the Free Software Foundation, either version 3 of the License, or
##    (at your option) any later version.
##
##    This program is distributed in the hope that it will be useful,
##    but WITHOUT ANY WARRANTY; without even the implied warranty of
##    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##    GNU General Public License for more details.
##
##    You should have received a copy of the GNU General Public License
##    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import wx
import wx.html
import wx.lib.scrolledpanel as scrolled
import wx.lib.agw.pybusyinfo as PBI

import codecs

from configuracion_vipera import proy_por_defecto as por_defecto
from i18n_vipera import t

try:
    import feedparser
except:
    print u'Módulo feedparser no se encontró / feedparser module not found'

def obtener_rss(origen):
    '''Devuelve estructura de rss'''
    # Recogemos noticias.
    try:
        d = feedparser.parse(origen)
        # Revolvemos noticias.
        return d["items"]
    except: return list()

class panel_rss(scrolled.ScrolledPanel):
    '''Panel de noticias RSS'''
    def __init__(self, parent, idioma = None):
        '''Constructor de clase'''
        # Llamamos al constructor del padre.
        scrolled.ScrolledPanel.__init__(self, parent, -1)
        # Mensaje de inicio...
        mensaje = t(u"Buscando noticias...", idioma)
        busy = PBI.PyBusyInfo(mensaje, parent=None, title=t(u"Un momento...", idioma))
        wx.Yield()
        # Buscamos noticias, si las hay.
        noticias = obtener_rss(por_defecto["rss"])
        num_noticias = len(noticias)
        # Recuperamos noticias.
        ret = list()
        for i in noticias:
            titulo = i['title']
            sumario = i['summary']
            fecha = i['date']
            url = i['link']
            ret.append((fecha, titulo, url, sumario))
        # Sizer principal.
        bSizer1 = wx.BoxSizer( wx.VERTICAL )
        # Quitamos el mensaje de inicio.
        del busy
        indice = 0
        for i in range(num_noticias):
            # Creamos filas y columnas con Sizer y FlexGridSizer.
            fgSizer1 = wx.FlexGridSizer(100, 1, 5, 5)
            fgSizer1.AddGrowableCol(0)
            fgSizer1.AddGrowableCol(1)
            fgSizer1.AddGrowableCol(2)
            fgSizer1.AddGrowableCol(3)
            fgSizer1.SetFlexibleDirection(wx.BOTH)
            fgSizer1.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
            bSizer2 = wx.BoxSizer(wx.HORIZONTAL)
            fgSizer2 = wx.FlexGridSizer(2, 2, 0, 0)
            fgSizer2.AddGrowableCol(0)
            fgSizer2.AddGrowableCol(1)
            fgSizer2.AddGrowableCol(2)
            fgSizer2.SetFlexibleDirection(wx.BOTH)
            fgSizer2.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
            # Título.
            m_staticText2 = wx.StaticText(self, -1, t(u"Título", idioma))
            m_staticText2.Wrap(-1)
            fgSizer2.Add(m_staticText2, 0, wx.ALIGN_CENTER|wx.ALL, 5)
            # Fecha.
            m_staticText1 = wx.StaticText(self, -1, t(u"Fecha", idioma))
            m_staticText1.Wrap(-1)
            fgSizer2.Add(m_staticText1, 0, wx.ALIGN_CENTER|wx.ALL, 5)
            # Incluir título.
            m_textCtrl_titulo = wx.TextCtrl(self, -1, ret[indice][1], style = wx.TE_READONLY|wx.NO_BORDER|wx.TE_CENTRE)
            m_textCtrl_titulo.SetForegroundColour(wx.Colour(255, 255, 255))
            m_textCtrl_titulo.SetBackgroundColour(wx.Colour(0, 128, 255))
            fgSizer2.Add(m_textCtrl_titulo, 0, wx.ALL|wx.EXPAND, 5)
            # Incluir fecha.
            m_textCtrl_fecha = wx.TextCtrl(self, -1, ret[indice][0], style = wx.TE_READONLY|wx.NO_BORDER|wx.TE_CENTRE)
            m_textCtrl_fecha.SetForegroundColour( wx.Colour(255, 128, 0))
            m_textCtrl_fecha.SetBackgroundColour(wx.Colour(255, 255, 255))
            fgSizer2.Add(m_textCtrl_fecha, 0, wx.ALL|wx.EXPAND, 5)
            # Lo incluimos en el sizer correspondiente.
            bSizer2.Add(fgSizer2, 1, wx.EXPAND, 5)
            fgSizer1.Add(bSizer2, 1, wx.EXPAND, 5)
            # Datos de URL.
            m_hyperlink = wx.HyperlinkCtrl(self, -1, ret[indice][2], ret[indice][2], style = wx.HL_DEFAULT_STYLE )
            fgSizer1.Add(m_hyperlink, 0, wx.ALL|wx.EXPAND, 5)
            # Datos de sumario en html.
            m_htmlWin_sumario = wx.html.HtmlWindow(self, -1, size = wx.Size(300,50), style = wx.html.HW_SCROLLBAR_AUTO)
            fich_aux = codecs.open(por_defecto['f_tmp_html'],'w','utf-8')
            fich_aux.write(ret[indice][3])
            fich_aux.close()
            m_htmlWin_sumario.LoadPage(por_defecto['f_tmp_html'])
            m_htmlWin_sumario.Enable(False)
            fgSizer1.Add(m_htmlWin_sumario, 0, wx.ALL|wx.EXPAND, 5 )
            # Linea de separación.
            m_staticline = wx.StaticLine( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_HORIZONTAL )
            fgSizer1.Add(m_staticline, 0, wx.EXPAND |wx.ALL, 5 )
            # Todo al sizer.
            bSizer1.Add( fgSizer1, 0, wx.ALL|wx.EXPAND, 5 )
            # Aumentamos el índice para la siguiente noticia.
            indice += 1
        # Lo incluimos en el sizer padre.
        self.SetSizer( bSizer1 )
        self.Layout()
        # Configuramos el scrolled panel.
        self.SetupScrolling()

class Dialogo_rss(wx.Dialog):
    '''Diálogo de RSS'''
    def __init__(self, parent, idioma = None):
        '''Cosntructor de clase'''
        wx.Dialog.__init__(self, parent, -1, title = t(u"Noticias", idioma), 
                           pos = wx.DefaultPosition, 
                           size = wx.Size(500,375), 
                           style = wx.DEFAULT_DIALOG_STYLE)
        self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize)
        bSizer = wx.BoxSizer(wx.VERTICAL)
        self.m_panel_base = wx.Panel(self, -1)
        rss = panel_rss(self.m_panel_base, idioma)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(rss, 1, wx.ALL|wx.EXPAND, 5)
        self.m_panel_base.SetSizer(sizer)
        bSizer.Add(self.m_panel_base, 1, wx.EXPAND |wx.ALL, 5)
        m_sdbSizer1 = wx.StdDialogButtonSizer()
        self.m_sdbSizer1OK = wx.Button(self, wx.ID_OK)
        m_sdbSizer1.AddButton(self.m_sdbSizer1OK)
        m_sdbSizer1.Realize()
        bSizer.Add(m_sdbSizer1, 0, wx.EXPAND, 5)
        self.SetSizer(bSizer)
        self.Layout()
        self.Centre( wx.BOTH )
